<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:include="common/common"></head>
<body>

<!--Header-part-->
<div id="header">
    <h1><a href="dashboard.html">Matrix Admin</a></h1>
</div>

<!--top-Header-menu-->
<div th:include="common/nav :: nav"></div>
<div th:include="common/menu :: menu"></div>

<div id="content">

    <div class="container-fluid">
        <hr/>
        <div class="row-fluid">
            <div class="span12">

                <div class="widget-box">
                    <div class="widget-title"> <span class="icon"><i class="icon-th"></i></span>
                        <h5>用户列表</h5>
                    </div>
                    <form class="form-inline">
                        <div class="form-group">
                            <label >编号:</label>
                            <input type="text" class="form-control" id="id-search" placeholder="编号:"/>
                        </div>
                        <div class="form-group">
                            <label >名称:</label>
                            <input type="text" class="form-control" id="name-search" placeholder="名称"/>
                        </div>
                        <div class="form-group">
                            <label class="control-label">状态:</label>
                            <select id="status-search"  class="form-control">
                                <option value="">全部</option>
                                <option value="1">启用</option>
                                <option value="0">禁用</option>
                            </select>
                        </div>
                        <button type="button"  onclick="search();" class="btn btn-primary">查询</button>
                        <button shiro:hasPermission="/admins/add" type="button"  onclick="$('#addAdmin').modal();" class="btn btn-primary" style="float: right; margin-right: 1px;">新增</button>
                        <button shiro:hasPermission="/admins/delete" type="button"  onclick="delByID();" class="btn btn-primary" style="float: right; margin-right: 1px;">删除</button>
                        <button shiro:hasPermission="/admins/saveAdminRole" type="button"  onclick="allotRole();" class="btn btn-primary" style="float: right; margin-right: 1px;">分配角色</button>
                        <button shiro:hasPermission="/admins/saveAdminEnable" type="button" onclick="changeEnable();" class="btn btn-primary" style="float: right; margin-right: 1px;">开启/禁用</button>
                    </form>

                    <div class="widget-content nopadding">
                        <table class="table table-striped table-bordered" cellspacing="0" width="100%" id="datatable" >
                            <thead>
                            <tr>
                                <th>
                                    <input type="checkbox" class="checkall" />
                                </th>
                                <th>ID</th>
                                <th>管理员名称</th>
                                <th>是否启用</th>
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!--分配弹框-->
<div class="modal fade bs-example-modal-sm"  id="selectRole" tabindex="-1" role="dialog" aria-labelledby="selectRoleLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="selectRoleLabel">分配角色</h4>
            </div>
            <div class="modal-body">
                <form id="boxRoleForm" >

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" onclick="saveAdminRoles();" class="btn btn-primary">Save</button>
            </div>
        </div>
    </div>
</div>
<!--添加用户弹框-->
<div class="modal fade" id="addAdmin" tabindex="-1" role="dialog" aria-labelledby="addroleLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="addroleLabel">添加用户</h4>
            </div>
            <div class="modal-body">
                <form id="userForm">
                    <div class="form-group">
                        <label  class="control-label">用户名:</label>
                        <input type="text" class="form-control" name="username" id="username" placeholder="请输入用户名"/>
                        <span class="btn-action single glyphicons circle_question_mark" data-toggle="tooltip" data-placement="top" data-original-title="必填"><i></i></span>
                    </div>
                    <div class="form-group">
                        <label  class="control-label">密码:</label>
                        <input type="password" class="form-control" id="password" name="password"  placeholder="请输入密码4位以上"/>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" onclick="addAdmin();" class="btn btn-primary">Save</button>
            </div>
        </div>
    </div>
</div>
<script th:src="@{/js/jquery-1.11.2.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<script th:src="@{/js/jquery.dataTables.min.js}"></script>
<script th:src="@{/js/layer.js}"></script>
<script type="text/javascript">
    $(".checkall").click(function () {
        var check = $(this).prop("checked");
        $(".checkchild").prop("checked", check);
    });

    //分页显示DataTable
    var table;
    $(document).ready(function () {
        table = $('#datatable').DataTable( {
            "searching" : false,
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "serverSide": true,//开启服务器模式，使用服务器端处理配置datatable
            //"processing": true,//开启读取服务器数据时显示正在加载中……特别是大数据量的时候，开启此功能比较好

            ajax : function(data, callback, settings) {
                //封装请求参数
                var param = getQueryCondition(data);

                $.ajax({
                    type: "GET",
                    url: '/admins',
                    cache : false,  //禁用缓存
                    data:param,    //传入已封装的参数
                    dataType: "json",
                    success: function(result) {
                        //封装返回数据  如果参数相同，可以直接返回result
//                        var returnData = {};
//                        returnData.draw = result.draw;//这里直接自行返回了draw计数器,应该由后台返回
//                        returnData.recordsTotal = result.recordsTotal;//总记录数
//                        returnData.recordsFiltered = result.recordsFiltered;//后台不实现过滤功能，每次查询均视作全部结果
//                        returnData.data = result.data;
                        //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                        //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                        callback(result);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg("查询失败");
                    }
                });
            },
            "columns": [
                {
                    "sClass": "text-center",
                    "data": "id",
                    "render": function (data, type, full, meta) {
                        return '<input type="checkbox"  class="checkchild"  value="' + data + '" />';
                    },
                    "bSortable": false
                },
                { "data": "id" },
                { "data": "username" },
                { "data": "enable" },
            ],
            columnDefs:[
                { "orderable": false, "targets": 1 },
                { "orderable": false, "targets": 2 },
                {
                    "orderable": false,
                    "render": function(data, type, row) {
                        if(data==1){
                            return "启用";
                        }else{
                            return "禁用";
                        }
                    },
                    "targets": 3
                },
            ],

        } );
    });

    function search(){
        table.ajax.reload();
    }
    //封装查询参数
    function getQueryCondition(data){
        var param = {};
        //组装排序参数


        param.id = $("#id-search").val();//查询条件
        param.username = $("#name-search").val();//查询条件
        param.enable = $("#status-search").val();//查询条件
        //组装分页参数
        param.start = data.start;
        param.length = data.length;
        param.draw = data.draw;
        return param;
    }

    //添加管理员
    function addAdmin() {
        var username = $("#username").val();
        var password = $("#password").val();
        if(username == "" || username == undefined || username == null){
            return layer.msg('用户名不能为空', function(){
                //关闭后的操作
            });
        }
        if(password.length<4||password.length>=16){
            return layer.msg('密码长度为4-16', function(){
                //关闭后的操作
            });
        }

        $.ajax({
            cache:true,
            type:'POST',
            url:'admins/add',
            data:$('#userForm').serialize(),
            async: false,
            success: function(data) {
                if(data.status == 200){
                    $('#addAdmin').modal('hide');
                    layer.msg('保存成功');
                    table.ajax.reload();
                }else(data.status == 500)
                {
                    $('#addAdmin').modal('hide');
                    layer.msg(data.error);
                }
            }
        });
    }

    //删除管理员
    function delByID() {
        //jQuery获取多选按钮的值
        var id = [];
        $(".checkchild:checked").each(function(){
            id.push($(this).val());
        });
        if ($(".checkchild:checked").length < 1) {
            layer.msg('请选择一条数据');
            return;
        }
        var parm = {"id":id};
        layer.confirm('您确定要删除这些用户吗？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            $.ajax({
                cache: true,
                type: "POST",
                url: 'admins/delete',
                data: parm,
                dataType:'json',
                async: false,
                success: function (data) {
                    if (data.status == 200) {
                        layer.msg('删除成功');
                        table.ajax.reload();
                    } else {
                        layer.msg(data.error);
                    }
                }
            });
        });
    }

    //弹出选择角色的框
    function allotRole(){
        var id = $(".checkchild:checked").val();
        if ($(".checkchild:checked").length < 1)
        {
            layer.msg('请选择一条数据');
            return;
        }
        if ($(".checkchild:checked").length > 1)
        {
            layer.msg('一次只能修改一条数据');
            return;
        }
        $.ajax({
            async:false,
            type : "POST",
            data:{uid:id},
            url: 'roles/rolesWithSelected',
            dataType:'json',
            success: function(data){
                if(data.status == 200){
                    $("#boxRoleForm").empty();
                    var htm = "<input type='hidden' name='uid' value='"+id+"'>";
                    for(var i=0;i<data.data.length;i++){
                        htm += "<div class='checkbox'><label><input type='checkbox' name='id' value='"+data.data[i].id+"'";
                        if(data.data[i].selected==1){
                            htm += " checked='checked'";
                        }
                        htm +="/>"+data.data[i].name+"</label></div>";
                    }
                    $("#boxRoleForm").append(htm);
                }
            }
        });

        $('#selectRole').modal();
    }
    //保存角色
    function saveAdminRoles() {

        $.ajax({
            cache: true,
            type: "POST",
            url:'admins/saveAdminRoles',
            data:$('#boxRoleForm').serialize(),
            async: false,
            success: function(data) {
                if(data.status == 200){
                    $('#selectRole').modal('hide');
                    layer.msg('保存成功');
                }else{
                    $('#selectRole').modal('hide');
                    layer.msg(data.error);
                }
            }
        })
    }
    //开启/禁用管理员
    function changeEnable() {
        //jQuery获取多选按钮的值
        var id = [];
        $(".checkchild:checked").each(function(){
            id.push($(this).val());
        });
        if ($(".checkchild:checked").length < 1) {
            layer.msg('请选择一条数据');
            return;
        }
        var parm = {"id":id};
        layer.confirm('您确定要启用/禁用这些用户吗？', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            $.ajax({
                cache: true,
                type: "POST",
                url: 'admins/saveAdminEnable',
                data: parm,
                dataType:'json',
                async: false,
                success: function (data) {
                    if (data.status == 200) {
                        layer.msg('操作成功');
                        table.ajax.reload();
                    } else {
                        layer.msg(data.error);
                    }
                }
            });
        });
    }

</script>
</body>
</html>